﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace DeviceManager.DataAccessLayer
{
    public class DeviceDbOperation:IDatabaseOperation<THIETBI>
    {
        QLThietBiEntities devicemanager;
        #region IDatabaseOperation<T> Members

        public int SaveRecord(THIETBI record)
        {
            try
            {
                using (devicemanager = new QLThietBiEntities())
                {
                    devicemanager.THIETBIs.Add(record);
                    devicemanager.SaveChanges();
                }
                return (int)record.ThietBiID;
            }
            catch
            {
                return -1;
            }
        }

        public bool UpdateRecord(THIETBI record)
        {
            using (devicemanager = new QLThietBiEntities())
            {
                devicemanager.THIETBIs.Find(record.ThietBiID);
                devicemanager.SaveChanges();
                return true;
            }
        }

        public List<THIETBI> GetRecord(THIETBI record)
        {
            devicemanager = new QLThietBiEntities();
            IQueryable<THIETBI> custQuery = devicemanager.THIETBIs.AsQueryable<THIETBI>();
            if (!string.IsNullOrEmpty(record.TenThietBi))
                custQuery = custQuery.Where(c => c.TenThietBi.Contains(record.TenThietBi));
            if (!string.IsNullOrEmpty(record.MaThietBi))
                custQuery = custQuery.Where(c => c.MaThietBi.Contains(record.MaThietBi));
            if (record.ThietBiID != 0 && record.ThietBiID != null)
                custQuery = custQuery.Where(c => c.ThietBiID == record.ThietBiID);
            return custQuery.ToList();
        }

        public bool DeleteRecord(THIETBI record)
        {

            using (devicemanager = new QLThietBiEntities())
            {
                var cust = devicemanager.THIETBIs.FirstOrDefault(c => c.ThietBiID == record.ThietBiID);
                devicemanager.THIETBIs.Remove(cust);
                devicemanager.SaveChanges();
                return true;
            }
        }

        #endregion
    }
}
